<?php

/**
 * 极光redis处理
 */

namespace push;

use app\common\lib\RedisKey;
use app\common\lib\RespCode;
use custom\Curl;
use custom\Log;
use custom\Redis;
use think\Exception;

class Aurora2 {

    /*消息类型*/
    const TYPE1 = 1; // 经纪人消息页
    const TYPE2 = 2; // 工作台-客户
    const TYPE3= 3; // 房源详情

    /**
     * 定制需求分组
     */
    const DEMAND_GROUP = [
        // 城市code
        'city_code'     => RedisKey::TAG_USER_DEMAND_CITY,
        // 区域code
        'area_code'     => RedisKey::TAG_USER_DEMAND_AREA,
        // 价格区间 100-200
        'price_section' => RedisKey::TAG_USER_DEMAND_PRICE,
        // 面积区间 100-200
        'area_section'  => RedisKey::TAG_USER_DEMAND_M,
        // 小区id（非必传）
        'village'       => RedisKey::TAG_USER_DEMAND_VILLAGE,
        // 商圈id（非必传）
        'business'      => RedisKey::TAG_USER_DEMAND_BUSINESS,
        // 不限 (非必传)
        'unlimited'     => RedisKey::TAG_USER_DEMAND_UNLIMITED,
    ];

    /**
     * 配置
     * @var array
     */
    protected static $configs = [
        'appKey'       => 'c0ef30884758618f1334461e',
        'masterSecret' => '1570136ee6da68cfc6b93805',
    ];

    /**
     * 需要的id
     * @param $data 参数
     * @param $id 需求id
     */
    public static function demandGroup($data, $id) {
        $redis = Redis::getInstance();
        foreach (self::DEMAND_GROUP as $field => $redisKey) {
            if (!empty($data[$field])) {
                $redisKey = "{$redisKey}_{$data[$field]}";
                $redis->sadd($redisKey, $id);
            }
        }
    }

    /**
     *
     * @param $cid 极光推送唯一标识
     * @param $registrationIds 极光用户设备号
     * @param $title title  推送标题
     * @param int $type 类型：
     * @return bool
     * @throws Exception
     */
    public static function push($cid, $registrationIds, $title, $type) {
        $url = "https://api.jpush.cn/v3/push";
        $data = [
            'cid'          => $cid,
            //平台
            'platform'     => ['ios', 'android'],
            //推送设备
            'audience'     => [
                'registration_id' => [$registrationIds],
            ],
            //通知内容体
            'notification' => [
                'android' => [
                    'alert'         => $title,
                    'style'         => 1,//通知栏样式类型
                    'extras'        => [
                        'type' => $type,
                    ]
                ],
                'ios'     => [
                    'alert'  => $title,
                    'badge'=>1,//	应用角标
                    'extras' => [
                        'type' => $type,
                    ]
                ],
            ],
            'options'      => [
                'apns_production' => (bool)config('global.product'),
            ],
        ];
        static::request($url, json_encode($data), 'POST');
        return true;
    }

    /**
     * 获取推送唯一标识
     * @param $count
     * @return mixed
     * @throws Exception
     */
    public static function getCid($count) {
        $url = "https://api.jpush.cn/v3/push/cid?count={$count}";
        $res = static::request($url);
        return $res['cidlist'];
    }

    /**
     * 请求三方调用
     * @param $url
     * @param array $data
     * @param string $mth
     * @return bool
     * @throws Exception
     */
    public static function request($url, $data = [], $mth = 'GET') {
        $conf = self::$configs;
        $curl = Curl::getInstance();
        $curl->setHeader(['Authorization' => "Basic " . base64_encode("{$conf['appKey']}:{$conf['masterSecret']}")]);
        $res = $curl->xhr($mth, $url, $data);
        is_array($data) && $data = json_encode($data);
        Log::write("极光推送：|$url|" . $data . '|res:' . $res, 'aurora.log');
        $res = json_decode($res, true);
        if (!$res || isset($res['code'])) {
            throw new Exception('推送获取失败',RespCode::PARAMS_ERR);
        }
        return $res;
    }
}